/*
 *  Copyright © OpenAtom Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.openatom.ubml.model.common.definition.commonmodel.collection;

import org.openatom.ubml.model.common.definition.cef.collection.BaseList;
import org.openatom.ubml.model.common.definition.cef.util.DataValidator;
import org.openatom.ubml.model.common.definition.commonmodel.IGspCommonObject;
import org.openatom.ubml.model.common.definition.commonmodel.IObjectCollection;
import org.openatom.ubml.model.common.definition.commonmodel.entity.GspCommonObject;

/**
 * The Collection Of Common Object
 *
 * @ClassName: GspObjectCollection
 * @Author: Benjamin Gong
 * @Date: 2021/1/11 17:13
 * @Version: V1.0
 */
public class GspObjectCollection extends BaseList<IGspCommonObject> implements IObjectCollection, Cloneable {
    private static final long serialVersionUID = 1L;
    private IGspCommonObject parentObject;

    /**
     * 创建节点集合
     *
     * @param parentObject 父结点
     */
    public GspObjectCollection(IGspCommonObject parentObject) {
        this.parentObject = parentObject;
    }

    // region ICloneable Members

    /**
     * 克隆
     *
     * @param parentObj 父节点
     * @return
     */
    public final GspObjectCollection clone(IGspCommonObject parentObj) {
        GspObjectCollection newObj = new GspObjectCollection(parentObj);
        for (IGspCommonObject item : this) {
            newObj.add(((GspCommonObject)item).clone(parentObj));
        }
        return newObj;
    }

    // endregion

    /**
     * 集合所属父节点
     */
    @Override
    public IGspCommonObject getParentObject() {
        return parentObject;
    }

    @Override
    public boolean add(IGspCommonObject obj) {
        DataValidator.checkForNullReference(obj, "obj");
        boolean result = super.add(obj);
        obj.setParentObject(getParentObject());
        if (getParentObject() != null) {
            obj.setBelongModel(getParentObject().getBelongModel());
        }
        return result;
    }

    private IGspCommonObject getByID(String id) {
        for (IGspCommonObject item : this) {
            if (id.equals(item.getID())) {
                return item;
            }
        }
        return null;
    }

    public void remove(String id) {
        IGspCommonObject obj = getByID(id);
        if (obj != null)
            super.remove(obj);
    }
}